package com.zbj.data.jpa.config;

import com.zbj.data.jpa.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import java.util.Map;

/**
 * JPAMasterDataSourceConfig
 * 默认事务管理名称为: transactionManager
 * @EnableTransactionManagement 开启事务注解支持 等同于xml配置方式的 <tx:annotation-driven />
 *
 * 查询策略配置: queryLookupStrategy 有三种值可以配置
 * 1、create-if-not-found(默认)：如果通过 @Query指定查询语句，则执行该语句，如果没有，则看看有没有@NameQuery指定的查询语句，如果还没有，则通过解析方法名进行查询
 * 2、create：通过解析方法名字来创建查询。即使有 @Query，@NameQuery都会忽略
 * 3、use-declared-query：通过执行@Query定义的语句来执行查询，如果没有，则看看有没有通过执行@NameQuery来执行查询，还没有则抛出异常
 * @author weigang
 * @create 2017-09-10
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.zbj.data.jpa.repository",
		entityManagerFactoryRef="entityManagerFactoryPrimary",
		transactionManagerRef="transactionManagerPrimary"
//		, queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND // 默认值
)
public class JPAMasterDataSourceConfig {

	@Autowired
	private JpaProperties jpaProperties;

	@Autowired
	private DynamicDataSource dataSource;

	@Primary
	@Bean(name = "entityManagerPrimary")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
	}

	@Primary
	@Bean(name = "entityManagerFactoryPrimary")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
		return builder
				.dataSource(dataSource)
				.properties(getVendorProperties(dataSource))
				.packages("com.zbj.data.jpa.entity") //设置实体类所在位置
				.persistenceUnit("primaryPersistenceUnit")
				.build();
	}

	private Map<String, String> getVendorProperties(DynamicDataSource dataSource) {
		return jpaProperties.getHibernateProperties(dataSource);
	}

	@Primary
	@Bean(name = "transactionManagerPrimary")
	public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
	}
}